package com.vhly.ddxdecompiler.dexreader.file.mixeditem;

import com.vhly.ddxdecompiler.dexreader.file.DexFile;
import com.vhly.ddxdecompiler.dexreader.io.DexInputStream;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;

/**
 * Created by IntelliJ IDEA.
 * User: vhly
 * Date: 2009-10-15
 * Time: 12:39:34
 *
 * @author vhly[FR]
 */
public final class AnnotationSetItem extends OffsettedItem {

    private Vector<AnnotationItem> items;

    private int[] offsets;

    private DexFile dex;

    public AnnotationSetItem(DexFile dexFile) {
        super(4, 0);
        items = new Vector<AnnotationItem>();
        dex = dexFile;
    }

    /**
     * 读取数据
     *
     * @param din 输入流
     * @throws java.io.IOException 异常
     */
    public void read(DexInputStream din) throws IOException {
        int size = din.readInt();
        if (size > 0) {
            offsets = new int[size];
            AnnotationItem item;
            for (int i = 0; i < size; i++) {
                offsets[i] = din.readInt();
                item = new AnnotationItem(dex);
                item.offset = offsets[i];
                items.add(item);
            }
        }
    }

    /**
     * 输出数据
     *
     * @param dout 输出流
     * @throws java.io.IOException 异常
     */
    public void write(DataOutputStream dout) throws IOException {
    }

    public void reloc(ByteArrayInputStream bin, int offset) throws IOException {
        int size = items.size();
        int off;
        AnnotationItem item;
        DataInputStream din = new DataInputStream(bin);
        DexInputStream dxin = new DexInputStream(din, 1);
        for (int i = 0; i < size; i++) {
            item = items.elementAt(i);
            bin.reset();
            off = item.offset;
            bin.skip(off - offset);
            dxin.setOffset(off);
            item.read(dxin);
        }
        dxin.close();
        din.close();
    }

    public AnnotationItem[] items(){
        AnnotationItem[] ret = null;
        if(!items.isEmpty()){
            ret = new AnnotationItem[items.size()];
            items.copyInto(ret);
        }
        return ret;
    }

    public Annotation getItemByType(String key){
        Annotation ret = null;
        if(!items.isEmpty()){
            for(AnnotationItem item : items){
                Annotation ann = item.getAnno();
                String s = ann.getType().item.toString();
                if(s.equals(key)){
                    ret = ann;
                    break;
                }
            }
        }
        return ret;
    }
}
